# 竞赛controller层
from flask import Blueprint, request
import json
import service.RaceService as RaceService
from utils import Token

# 创建race蓝图
race = Blueprint('race', __name__)


@race.before_request
def is_login():
    return Token.verify_auth_token(request)


@race.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, HEAD, OPTIONS')
    response.headers.add('Access-Control-Allow-Headers', '*')
    return response


# 获取竞赛列表
@race.route('/race/getRaceList', methods=['POST'])
def race_getRaceList():
    data = request.get_data()
    data = json.loads(data)

    # 竞赛状态,0为全部，1为已提交，2为未提交
    status = int(data['status'])
    # 比赛类别，用来标签筛选用
    category = data['category']
    uuid = int(data['uuid'])
    # 0为全部，1为训练赛，2为竞赛
    raceCategory = data['raceCategory']
    # 搜索内容,空则不进行搜索返回全部内容
    search = data['search']

    result = RaceService.service_race_getRaceList(status, category, raceCategory, search, uuid)
    return result


# 获取竞赛详情
@race.route('/race/detail', methods=['GET'])
def race_detail():
    raceId = int(request.args.get('raceId', type=str, default=None))
    uuid = int(request.args.get('uuid', type=str, default=None))
    result = RaceService.service_race_detail(raceId, uuid)
    return result


# 竞赛排名
@race.route('/race/rank', methods=['GET'])
def race_rank():
    raceId = int(request.args.get('raceId', type=str, default=None))
    result = RaceService.service_race_rank(raceId)
    return result


# 提交比赛文件
@race.route('/race/submitFile', methods=['POST'])
def race_submitFile():
    raceId = int(request.form.get('raceId', type=str, default=None))
    uuid = int(request.form.get('uuid', type=str, default=None))
    file = request.files.get('file')
    result = RaceService.service_race_submitFile(raceId, uuid, file)
    return result
